﻿using System.Net;
using System.Web.SessionState;
using System.Globalization;
using System.Web.Caching;
using System.Collections;
using System.Collections.Generic;
using System.Web.Profile;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Web.Util;
using System.Web.Hosting;
namespace System.Web
{
    public class NetHttpContext : HttpContextBase
    {
        private WebHostWorkerRequest _wr;
        private IHttpHandler _currentHandler;
        private IDictionary _items = new Hashtable();
        private HttpRequestBase _request;
        private HttpResponseBase _response;
        private HttpServerUtilityBase _server;
        private HttpSessionStateBase _session;
        private NetHttpApplication _appInstance;
        //
        private SessionStateBehavior _sessionStateBehavior;
        private DateTime _utcTimestamp;
        private IHttpHandler _remapHandler;
        private INetHttpAsyncHandler _asyncAppHandler;
        private NetAspNetSynchronizationContext _syncContext;

        public NetHttpContext(WebHostWorkerRequest wr)
        {
            if (wr == null)
                throw new ArgumentNullException("wr");
            _wr = wr;
            Init(new NetHttpRequest(wr, this), new NetHttpResponse(wr, this));
        }
        public NetHttpContext(NetHttpRequest request, NetHttpResponse response)
        {
            Init(request, response);
            request.Context = this;
            response.Context = this;
        }
        internal NetHttpContext(WebHostWorkerRequest wr, bool initResponseWriter)
        {
            _wr = wr;
            Init(new NetHttpRequest(wr, this), new NetHttpResponse(wr, this));
            if (initResponseWriter)
                ((NetHttpResponse)_response).InitResponseWriter();
        }

        #region HttpContextBase

        public override void AddError(Exception errorInfo) { }
        public override void ClearError() { }
        public override object GetGlobalResourceObject(string classKey, string resourceKey) { return null; }
        public override object GetGlobalResourceObject(string classKey, string resourceKey, CultureInfo culture) { return null; }
        public override object GetLocalResourceObject(string virtualPath, string resourceKey) { return null; }
        public override object GetLocalResourceObject(string virtualPath, string resourceKey, CultureInfo culture) { return null; }
        public override object GetSection(string sectionName) { return null; }
        public override object GetService(Type serviceType) { return null; }
        public override void RemapHandler(IHttpHandler handler)
        {
            if (_wr != null)
            {
                if (CurrentNotification >= RequestNotification.MapRequestHandler)
                    throw new InvalidOperationException(string.Format("Invoke_before_pipeline_event {0}, {1}", "HttpContext.RemapHandler", "HttpApplication.MapRequestHandler"));
                string handlerType = null;
                string handlerName = null;
                if (handler != null)
                {
                    var type = handler.GetType();
                    handlerType = type.AssemblyQualifiedName;
                    handlerName = type.FullName;
                }
                _wr.SetRemapHandler(handlerType, handlerName);
            }
            _remapHandler = handler;
        }
        public override void RewritePath(string path) { }
        public override void RewritePath(string path, bool rebaseClientPath) { }
        public override void RewritePath(string filePath, string pathInfo, string queryString) { }
        public override void RewritePath(string filePath, string pathInfo, string queryString, bool setClientFilePath) { }
        public override void SetSessionStateBehavior(SessionStateBehavior sessionStateBehavior)
        {
            _sessionStateBehavior = sessionStateBehavior;
        }

        public override Exception[] AllErrors
        {
            get { return null; }
        }

        //public override HttpApplicationStateBase Application
        //{
        //    get { return NetApplicationInstance.Application; }
        //}

        //public override HttpApplication ApplicationInstance
        //{
        //    get { return _appInstance; }
        //    set { _appInstance = value; }
        //}

        public override Cache Cache
        {
            get { return null; }
        }

        public override IHttpHandler CurrentHandler
        {
            get { return _currentHandler; }
        }

        private RequestNotification _currentNotification = RequestNotification.BeginRequest;
        public new RequestNotification CurrentNotification
        {
            get { return _currentNotification; }
            set { _currentNotification = value; }
        }

        public override Exception Error
        {
            get { return null; }
        }

        public override IHttpHandler Handler
        {
            get { return null; }
            set { }
        }

        public override bool IsCustomErrorEnabled
        {
            get { return false; }
        }

        public override bool IsDebuggingEnabled
        {
            get { return true; }
        }

        public override bool IsPostNotification
        {
            get { return false; }
        }

        public override IDictionary Items
        {
            get { return _items; }
        }

        public override IHttpHandler PreviousHandler
        {
            get { return null; }
        }

        public override ProfileBase Profile
        {
            get { return null; }
        }


        public override HttpRequestBase Request
        {
            get { return _request; }
        }

        public override HttpResponseBase Response
        {
            get { return _response; }
        }

        public override HttpServerUtilityBase Server
        {
            get { return _server; }
        }

        public override HttpSessionStateBase Session
        {
            get { return _session; }
        }

        public override bool SkipAuthorization
        {
            get { return false; }
            set { }
        }

        public override DateTime Timestamp
        {
            get { return DateTime.Now; }
        }

        public override TraceContext Trace
        {
            get { return null; }
        }

        public override IPrincipal User
        {
            get { return null; }
            set { }
        }

        #endregion

        internal void ClearReferences()
        {
            _appInstance = null;
            //_handler = null;
            //_handlerStack = null;
            _currentHandler = null;
            //if (_isIntegratedPipeline)
            //{
            //    _items = null;
            //    _syncContext = null;
            //}
        }

        private void Init(NetHttpRequest request, NetHttpResponse response)
        {
            _request = request;
            _response = response;
            _utcTimestamp = DateTime.UtcNow;
        }

        public NetHttpApplication NetApplicationInstance { get; internal set; }

        internal WebHostWorkerRequest WorkerRequest
        {
            get { return _wr; }
        }

        internal void InternalEnd() { }

        public bool HideRequestResponse { get; set; }

        public bool DisableCustomHttpEncoder { get; set; }

        internal INetHttpAsyncHandler AsyncAppHandler
        {
            get { return _asyncAppHandler; }
            set { _asyncAppHandler = value; }
        }

        internal NetAspNetSynchronizationContext SyncContext
        {
            get
            {
                if (_syncContext == null)
                    _syncContext = new NetAspNetSynchronizationContext(NetApplicationInstance);
                return _syncContext;
            }
        }
    }
}
